import os
import random
import string

from flask import Flask, request, jsonify
from flask_cors import CORS
from qiniu import Auth, BucketManager, put_file, etag

access_key = 'AJLzx4IfvsFEFslZjazhVnsf9yJNtwiwouavw8vk'
secret_key = 'PRr3fVwZ-0IBAFyW2rOPsKV1X3AJAUruDWsZq7EZ'
bucket_name = 'liuzibing8168'
bucket_domain = 'https://photo.rodvl.top/'

zone = Flask(__name__)
CORS(zone)
q = Auth(access_key, secret_key)
bucket = BucketManager(q)


@zone.route('/')
def selectList():
    # 前缀
    prefix = None
    # 列举条目
    limit = 10
    # 列举出除'/'的所有文件以及以'/'为分隔的所有前缀
    delimiter = None
    # 标记
    marker = None
    ret, eof, info = bucket.list(bucket_name, prefix, marker, limit, delimiter)
    print('==========>RET', ret)
    print('==========>EOF', eof)
    print('==========>INFO', info)
    return jsonify(ret)


class UpFile(object):
    # 生成5位小写字母加数字的随机文件名
    @staticmethod
    def random_name():
        return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))

    def upload_img(self, fn, sfx):
        key = self.random_name() + sfx
        token = q.upload_token(bucket_name, key, 3600)
        ret, info = put_file(token, key, fn)
        print('------RET:', ret)
        print('------INFO:', info)
        if (ret is not None) and ret['key'] == key and ret['hash'] == etag(fn):
            return bucket_domain + key
        else:
            self.notify("qiniu-fileup")
            return False

    def notify(title, text):
        print("osascript -e 'display notification \"{}\" with title \"{}\"'".format(text, title))


@zone.route('/upload', methods=['post'])
def upload_file_qiNiu():
    if request.method == 'POST':
        up = UpFile()
        f = request.files.get('file')
        filename, sfx = os.path.splitext(f.filename)
        upload_file_name = "uploadFile" + sfx
        f.save(upload_file_name)
        qiNiu_url = up.upload_img(upload_file_name, sfx)

        if qiNiu_url:
            up.notify("qiniu-fileup")
        else:
            up.notify("qiniu-fileup")
        return qiNiu_url


if __name__ == '__main__':
    zone.run(debug=type)
